// 采购来源信息
function purchaseOriginHtml(sku, cnt, price, img, address) {
	// console.log('html了');
	// 确保address是一个对象且有默认值
    address = address || {};
    address.name = address.name || '';
    address.address_txt = address.address_txt || '';

	const html = `
		<div id="csp-purchase-info" style="font-size: 12px; background-color: white;border: 10px solid red;width: 300px; min-height: 500px; border-radius: 15px; position: fixed; right: 0px; top: 100px; z-index: 100000">
			<div id="csp-purchase-title" style="text-align: center; line-height: 50px;height: 60px; width: 100%; background-color: red; color: white; font-size: 25px">
				采购信息
			</div>
			<div style="padding: 5px; font-size: 15px;">

				<div>
					<span style="color: black;">收件人：</span>
					<span style="color: red;">${address.name}</span>
				</div>

				<div>
					<span style="color: black;">地址：</span>
					<span style="color: red;">${address.address_txt}</span>
				</div>

				<div>规格： ${sku}</div>
				<div>数量： ${cnt}</div>
				<div>卖出价： ${price * cnt}</div>
				<div>
					<image style="width: 300px;" src="${img}" />
				</div>
				<div id="csp-money"></div>
			</div>
		</div>
	`.split('\n')
	.map(line => line.trim())
	.join('');
	document.body.insertAdjacentHTML('afterbegin', html);
	var div = document.getElementById('csp-purchase-info');
	// console.log(div);
	var isDragging = false;
	let offsetX, offsetY;
	div.addEventListener('mousedown', (e) => {
        isDragging = true;
        offsetX = e.clientX - div.offsetLeft;
        offsetY = e.clientY - div.offsetTop;
        e.preventDefault(); // 阻止默认行为（如文本选择）
    });
    // 鼠标移动事件（绑定到document以覆盖整个视口）
    document.addEventListener('mousemove', (e) => {
        if (!isDragging) return;
        
        const newX = e.clientX - offsetX;
        const newY = e.clientY - offsetY;
        
        div.style.left = newX+'px';
        div.style.top = newY+'px';
    });
    // 鼠标释放事件
    document.addEventListener('mouseup', () => {
        isDragging = false;
    });
}

class CSP {

	domain = 'http://121.43.232.161';
	address_name = '';
	address_info = '';
	address_phone = '';

	constructor() {
		this.data = null
	}

	delay(ms) {
		return new Promise(resolve => setTimeout(resolve, ms))
	}

	async getContentJSData(greeting, tabid) {
		var jsresponse = await new Promise((resolve) => {
			chrome.tabs.sendMessage(tabid, {greeting: greeting}, (response) => {
				// console.log(response);
				if (chrome.runtime.lastError) {
					console.warn(chrome.runtime.lastError.message);
        			resolve(null);
				} else {
					resolve(response);
				}
			})
		});
		return jsresponse
	}
	// 打开页面等待页面加载完成 返回 tabid
	async createTabAndWaitForLoad(url) {
	  return new Promise((resolve, reject) => {
	    // 创建新标签页
	    chrome.tabs.create({ url, active: false }, (tab) => {
	      const tabId = tab.id;
	      
	      // 监听页面完成加载事件
	      const onUpdated = (updatedTabId, changeInfo, updatedTab) => {
	        if (updatedTabId === tabId && changeInfo.status === 'complete') {
	          // 移除监听器
	          chrome.tabs.onUpdated.removeListener(onUpdated);
	          resolve(tabId);
	        }
	      };
	      
	      // 添加监听器
	      chrome.tabs.onUpdated.addListener(onUpdated);
	      
	      // 设置超时，防止页面加载卡住
	      setTimeout(() => {
	        chrome.tabs.onUpdated.removeListener(onUpdated);
	        reject(new Error('页面加载超时'));
	      }, 30000); // 30秒超时
	    });
	  });
	}


	objectToUrlParams(obj) {
	  return Object.entries(obj)
	    .map(([key, value]) => {
	      // 忽略 null 和 undefined
	      if (value == null) return null;
	      // 对键和值进行编码
	      return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
	    })
	    .filter(pair => pair !== null) // 过滤掉无效项
	    .join('&'); // 拼接成字符串
	}

	async sendApi(api, reqData, post = 1) {
		const data = await this.storageGetPromise(['apptoken']);
		var post_url = this.domain + api;
		if (post) {
			var response = await fetch(post_url, {
				method: 'POST',
				headers: {
					'Content-Type': 'application/json',
	            	'apptoken': data.apptoken
				},
				body: JSON.stringify(reqData)
			});
		} else {
			//get 把 reqData 变成url传
			var params = this.objectToUrlParams(reqData);
			var response = await fetch(post_url + '?'+ params, {
				method: 'POST',
				headers: {
					'Content-Type': 'application/json',
	            	'apptoken': data.apptoken
				},
			});
		}
		const res = await response.json();
		return res;
	}

	// 掉线
	async disAccount(account) {
		this.sendApi('/chrome/disaccount', {id: account.id});
	}

	async getRawDataHtml(url) {
		const data = await this.storageGetPromise(['agent']);
		var response = await fetch(url, {
			method: 'GET',
			credentials: 'include',
			headers: {
				"Content-Type": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
				'User-Agent': data.agent,
			}
		});

		return await response.text();
	}

	getRawData(html) {
		const regex =  /window\.rawData\s*=\s*({.*?})\s*;/s;
		const match = html.match(regex);
		// console.log(match);
		if (!match) {
			return false;
		}
		const rawData = JSON.parse(match[1]);
		// console.log(rawData);
		return rawData;
	}

	// 接口相关
	// 发送 待收货订单数据到服务器
	async postSendOrderErp(send_order_data, message) {
		const post_url = this.domain + "/chrome/order/send";
		const reqData = {
			send_order_data: send_order_data
		};
		const data = await this.storageGetPromise(['cookies', 'apptoken']);
		// 请求数据库
		const response = await fetch(post_url, {
			method: 'POST',
			headers: {
				'Content-Type': 'application/json',
                'apptoken': data.apptoken
			},
			body: JSON.stringify(reqData)
		});

		var res = await response.json();
		// 这里可以通知 erp刷新
		chrome.tabs.sendMessage(message.erptabid, {greeting: 'sendInfo', info: res.message, code: res.code});
	}
	// 获取账号
	async getAccounts(acct_type = 1) {
		const account_url = this.domain + '/chrome/account/get?acct_type=' + acct_type;
		// 获取账号数据
		const data = await this.storageGetPromise(['cookies', 'apptoken']);
		const response = await fetch(account_url, {
			method: 'POST',
			headers: {
					'Content-Type': 'application/json',
                	'apptoken': data.apptoken
				},
		});
		const res = await response.json();
		if (res.code != 200) {
			// 这里可以通知erp页面 
			chrome.scripting.executeScript({
				target: {tabId: sender.tab.id},
				func: () => {
					alert('登录失败请查看弹出的新窗口');
				}
			});
			return 0;
		}

		return res.data;
	}

	// 浏览器相关
	async setPDDCookie(cookies) {
		for (var i = 0; i < cookies.length; i++) {
			const cookieone = {
				url: `https://mobile.yangkeduo.com`,
			    name: cookies[i].name,
			    value: cookies[i].value,
			    domain: `${cookies[i].domain}`,
			    path: cookies[i].path,
			    secure: cookies[i].secure,
			    httpOnly: cookies[i].httpOnly,
			    expirationDate: cookies[i].expirationDate
			};
			await this.setCookie(cookieone);
		}

	}

	/**
	 * 封装 chrome.storage.local.get 为返回 Promise 的函数
	 * @param {string|Array<string>|Object} keys 要获取的存储键
	 * @returns {Promise<Object>} 返回包含存储数据的 Promise
	 */
	storageGetPromise(keys) {
	    return new Promise((resolve, reject) => {
	        chrome.storage.local.get(keys, (result) => {
	            if (chrome.runtime.lastError) {
	                reject(chrome.runtime.lastError);
	            } else {
	                resolve(result);
	            }
	        });
	    });
	}

	StorageSetPromise(key, value) {
		return new Promise((resolve, reject) => {
	    	chrome.storage.local.set({ [key]: value }, () => {
	    		if (chrome.runtime.lastError) {
	    			reject(new Error(`存储失败: ${chrome.runtime.lastError.message}`));
	    			return;
	    		}
	      		resolve({ success: true, key, value });
	    	});
		});
	}

	// 获取tab
	getTabPromise(tabId){ 
	  	return new Promise((resolve) => {
	    	chrome.tabs.get(tabId, (tab) => {
	      		if (chrome.runtime.lastError) {
	        		console.warn(chrome.runtime.lastError.message);
	        		resolve(null);
	      		} else {
	        		resolve(tab);
	      		}
	    	});
	  	});
	}
	/*
	sendMessage 封装 await
	*/
	sendMessagePromise(tabId, message) {
		return new Promise((resolve) => {
			chrome.tabs.sendMessage(tabId, message, (response)=> {
				if (chrome.runtime.lastError) {
					resolve(null);
				} else {
					resolve(response);
				}
			});
		});
	}

	/**
	 * 封装 chrome.cookies.set 为返回 Promise 的函数
	 * @param {Object} cookie - 要设置的 Cookie 对象
	 * @returns {Promise<void>} - 返回一个 Promise，当 Cookie 设置成功时解析
	 */
	setCookie(cookie) {
	    return new Promise((resolve, reject) => {
	        chrome.cookies.set(cookie, (result) => {
	            if (chrome.runtime.lastError) {
	                reject(new Error(chrome.runtime.lastError.message));
	            } else {
	                resolve(result);
	            }
	        });
	    });
	}

	// async initData() {
	// 	this.data = await this.storageGetPromise(['cookies', 'apptoken']);
	// }

	async autoorderClear(message, sender, sendResponse) {
		// 重置下单页面tab缓存检测
		await this.StorageSetPromise('hand_order_tab', '');
		var check = await this.storageGetPromise(['hand_order_tab']);
		// console.log(check);
		if (check.hand_order_tab != '') {
			// 失败
			chrome.scripting.executeScript({
				target: {tabId: sender.tab.id},
				func: ()=> {
					alert('重置失败');
				}
			});
		} else {
			// 成功
			chrome.scripting.executeScript({
				target: {tabId: sender.tab.id},
				func: ()=> {
					alert('重置成功');
				}
			});
		}
	}

	async nowAccount(message) {
		const data = await this.storageGetPromise(['cookies', 'apptoken']);
		var personal_html = await this.getRawDataHtml("https://mobile.yangkeduo.com/personal.html");
		var rawData = this.getRawData(personal_html);
		if (rawData.stores.store.userInfo) {

		}

		// cookies 直接拿
		var cookies = await new Promise((resolve) => {
			chrome.cookies.getAll({
				url:  "https://mobile.yangkeduo.com",
			}, resolve);
		});

		// console.log(cookies);
        var reqData = {
            cookies: cookies,
            nikename: message.data
        }
        if (rawData && rawData.stores.store.userInfo) {
			reqData.userInfo = rawData.stores.store.userInfo;
		}
        fetch(this.domain + "/chrome/nowAccount", {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'apptoken': data.apptoken
            },
            body: JSON.stringify(reqData)
        });
	}

	// http://121.43.232.161/chrome/login
	login(message, sender, sendResponse) {
		const url = this.domain + "/chrome/login";
		chrome.storage.local.get(['apptoken'], (data)=> {
			fetch(url, {
				method: 'POST',
				headers: {
					'Content-Type': 'application/json',
                	'apptoken': data.apptoken
				}
			})
			.then(response => response.json())
			.then(res => sendResponse(res))
			.catch(error => sendResponse({code: 300, message: error}))
		});
	}

	async getSkuByDOM(message, sender, sendResponse) {

		console.log('DOM 方式');
		//查询 product_id 跟 url是否存在
		var checkReq = {
			platform_product_id: message.platform_product_id,
			url: message.url
		};
		var check_res = await this.sendApi('/chrome/parse/check', checkReq);
		if (check_res.code != 200) {
			chrome.tabs.sendMessage(sender.tab.id,{greeting: 'skuReady', is_refresh: message.is_refresh});
			return chrome.scripting.executeScript({
				target: {tabId: sender.tab.id},
				func: ()=> {
					alert('无需获取');
				}
			});
			
		}

		var accounts = await this.getAccounts(2);
		if (accounts.length == 0) {
			chrome.tabs.sendMessage(sender.tab.id,{greeting: 'skuReady', is_refresh: message.is_refresh});
			return chrome.scripting.executeScript({
				target: {tabId: sender.tab.id},
				func: ()=> {
					alert('请先添加关联账号');
				}
			});
		}

		var storage_data = await this.storageGetPromise(['agent']);
		var fail_account = '';

		// 采集开始
		for (var i = 0; i < accounts.length; i++) {
			const cookies = JSON.parse(accounts[i].cookies);
			await this.setPDDCookie(cookies);
			// 记录次数
			await this.sendApi('/chrome/account/times/log', {acct_id: accounts[i].id});
			
			//向前发送代码
			// 商品页面  message.url
			var ddtabId = await this.createTabAndWaitForLoad(message.url);
			// console.log(ddtabId);
			// await this.delay(2000);
			var response = await chrome.tabs.sendMessage(ddtabId, {greeting: 'getSkuByDOM'});
			var rawDataJson = response.rawData;
			// console.log('json',rawDataJson);

			// 关闭
			chrome.tabs.remove(ddtabId);

			if (rawDataJson == 'false') {
				fail_account = fail_account + `【账号${accounts[i].nikename} 没有获取到数据`;
				continue;
			}

			var rawData = JSON.parse(JSON.parse(rawDataJson));

			if (!rawData) {
				fail_account = fail_account + `【账号${accounts[i].nikename} 没有获取到数据，有可能需要验证】`;
				continue;
			}

			

			if (rawData.store.initDataObj.needLogin) {
				fail_account = fail_account + `【账号${accounts[i].nikename} 掉线了】`;
				continue;
			}
			
			if (rawData.store.initDataObj.goods.statusExplain == '商品已售罄，推荐以下相似商品') {
				fail_account = fail_account + `【账号${accounts[i].nikename} 商品已售罄，推荐以下相似商品】`;
				continue;
			}

			if (rawData.store.initDataObj.goods.skus && rawData.store.initDataObj.goods.skus[0].groupPrice == 0) {
				fail_account = fail_account + `【账号${accounts[i].nikename} 拉取失败】`;
				continue;
			}

			var costReq = {
				goods_id: rawData.store.initDataObj.goods.goodsID,
				title: rawData.store.initDataObj.goods.goodsName,
				platform_product_id: message.platform_product_id,
				url: message.url
			};

			var cost_res = await this.sendApi('/chrome/parse/cost', costReq);
			if (cost_res.code != 200) {
				fail_account = fail_account + ' ' + cost_res.message;
				break;
			}
			
			const reqData = {
				data: {
					platform_product_id: message.platform_product_id,
					rawData: JSON.stringify(rawData),
					pdd_goods_url: message.url
				}
			};
			const res = await this.sendApi('/chrome/raw/data', reqData);
			if (res.code == 200) {
				chrome.tabs.sendMessage(sender.tab.id,{greeting: 'skuReady', is_refresh: message.is_refresh});
				return;
			}
		}


		if (fail_account != '') {
			chrome.scripting.executeScript({
				target: {tabId: sender.tab.id},
				func: (fail_account)=> {
					alert(fail_account);
				},
				args: [fail_account]
			});
		}
		chrome.tabs.sendMessage(sender.tab.id,{greeting: 'skuReady', is_refresh: message.is_refresh});
		sendResponse({result: true});
	}


	// 采集商品
	async getSku(message, sender, sendResponse) {
		var accounts = await this.getAccounts(2);
		if (accounts.length == 0) {
			chrome.scripting.executeScript({
				target: {tabId: sender.tab.id},
				func: ()=> {
					alert('请先添加关联账号');
				}
			});
		}
		var storage_data = await this.storageGetPromise(['agent']);
		var fail_account = '';
		for (var i = 0; i < accounts.length; i++) {
			const cookies = JSON.parse(accounts[i].cookies);
			await this.setPDDCookie(cookies);
			// 记录次数
			await this.sendApi('/chrome/account/times/log', {acct_id: accounts[i].id});
			
			const html = await this.getRawDataHtml(message.url);
			// console.log(html);
			const rawData = this.getRawData(html);
			if (!rawData) {
				// 掉线了
				// chrome.scripting.executeScript({
				// 	target: {tabId: sender.tab.id},
				// 	func: (account)=> {
				// 		alert(`账号 ${account.nikename} 没有获取到数据，有可能需要验证`);
				// 	},
				// 	args: [accounts[i]]
				// });
				// continue;
				fail_account = fail_account + `【账号${accounts[i].nikename} 没有获取到数据，有可能需要验证】`;
				continue;
			}

			if (rawData.store.initDataObj.needLogin) {
				// 掉线了
				// chrome.scripting.executeScript({
				// 	target: {tabId: sender.tab.id},
				// 	func: (account)=> {
				// 		alert(`账号 ${account.nikename} 掉线了`);
				// 	},
				// 	args: [accounts[i]]
				// });
				// this.disAccount(accounts[i]);
				fail_account = fail_account + `【账号${accounts[i].nikename} 掉线了】`;
				continue;
			}

			if (rawData.store.initDataObj.goods.statusExplain == '商品已售罄，推荐以下相似商品') {
				// chrome.scripting.executeScript({
				// 	target: {tabId: sender.tab.id},
				// 	func: (account)=> {
				// 		alert(`账号 ${account.nikename} 显示商品已售罄`);
				// 	},
				// 	args: [accounts[i]]
				// });

				fail_account = fail_account + `【账号${accounts[i].nikename} 商品已售罄，推荐以下相似商品】`;
				continue;
			}

			if (rawData.store.initDataObj.goods.statusExplain == '商品已售罄，推荐以下相似商品') {
				continue;
			}
			
			const reqData = {
				data: {
					platform_product_id: message.platform_product_id,
					rawData: JSON.stringify(rawData),
					pdd_goods_url: message.url
				}
			};
			const res = await this.sendApi('/chrome/raw/data', reqData);
			if (res.code == 200) {
				chrome.tabs.sendMessage(sender.tab.id,{greeting: 'skuReady', is_refresh: message.is_refresh});
				return;
			}
		}

		if (fail_account != '') {
			chrome.scripting.executeScript({
				target: {tabId: sender.tab.id},
				func: (fail_account)=> {
					alert(fail_account);
				},
				args: [fail_account]
			});
		}
		chrome.tabs.sendMessage(sender.tab.id,{greeting: 'skuReady', is_refresh: message.is_refresh});
		sendResponse({result: true});
	}



	
	// fetch修改地址
	async fetchAddress(data, pdduid) {
		const requestBody = data;
		const requestHeaders = new Headers({
			'Accept': 'application/json, text/plain, */*',
			'Accept-Encoding': 'gzip, deflate, br, zstd',
			'Accept-Language': 'zh-CN,zh;q=0.9',
			'Content-Type': 'application/json;charset=UTF-8',
			// 'Cookie': 'api_id=GiTug2e+/+7wMADSMA51WADSA1WaG==; pdd_user_uin=12MCA7ZEPIK5VSZMKCV1TQAVQNI_GEXDA; ...', // 保留完整 Cookie
			'Origin': 'https://mobile.yangkeduo.com',
			'Priority': 'u=1, i',
			'Referer': 'https://mobile.yangkeduo.com/addresses.html' // 需补充完整 Referer
		});
		var url = "https://mobile.yangkeduo.com/proxy/api/api/origenes/address_info/" + data.address_id + '?pdduid=' + pdduid;
		const requestUrl = new URL(url);
		const response = await fetch(requestUrl, {
			method: 'POST',
			headers: requestHeaders,
			body: JSON.stringify(requestBody),
			credentials: 'include'
		});
		return await response.json();
	}

	
	// 获取省份
	async fetchAddr(url) {
		const requestHeaders = new Headers({
			'Accept': 'application/json, text/plain, */*',
			'Accept-Encoding': 'gzip, deflate, br, zstd',
			'Accept-Language': 'zh-CN,zh;q=0.9',
			'Content-Type': 'application/json;charset=UTF-8',
			// 'Cookie': 'api_id=GiTug2e+/+7wMADSMA51WADSA1WaG==; pdd_user_uin=12MCA7ZEPIK5VSZMKCV1TQAVQNI_GEXDA; ...', // 保留完整 Cookie
			'Origin': 'https://mobile.yangkeduo.com',
			'Priority': 'u=1, i',
			'Referer': 'https://mobile.yangkeduo.com/addresses.html' // 需补充完整 Referer
		});
		const requestUrl = new URL(url);

		const response = await fetch(requestUrl, {
			method: 'GET',
			headers: requestHeaders,
			credentials: 'include'
		});

		const res = await response.json();
		return res;
	}

	// 拼多多post
	async pddOrderPost(url, data) {
		const requestHeaders = new Headers({
			'Accept': 'application/json, text/plain, */*',
			'Accept-Encoding': 'gzip, deflate, br, zstd',
			'Accept-Language': 'zh-CN,zh;q=0.9',
			'Content-Type': 'application/json;charset=UTF-8',
			// 'Cookie': 'api_id=GiTug2e+/+7wMADSMA51WADSA1WaG==; pdd_user_uin=12MCA7ZEPIK5VSZMKCV1TQAVQNI_GEXDA; ...', // 保留完整 Cookie
			'Origin': 'https://mobile.yangkeduo.com',
			'Priority': 'u=1, i',
			'Referer': 'https://mobile.yangkeduo.com/order.html?order_sn='+ data.order_sn // 需补充完整 Referer
		});
		const response = await fetch(url, {
			method: 'POST',
			headers: requestHeaders,
			credentials: 'include',
			body: JSON.stringify(data)
		});
		if (!response.ok) {
			return {code: 500};
		}
		const res = await response.json();
		return res;
	}

	// 关闭自动下单
	async closeAuto(message, sender, sendResponse) {
		await this.StorageSetPromise('auto_order', 2);
		await this.StorageSetPromise('auto_pay', 2);
		this.autoOrderInfo('手动关闭了自动下单');
		// console.log('关闭自动成功');
	}

	async startAuto(message, sender, sendResponse) {
		await this.StorageSetPromise('auto_order', 1);
		await this.StorageSetPromise('auto_pay', 1);
		// console.log('开启自动成功');
	}

	// 自动下单流程
	async autoOrder(message, sender, sendResponse) {
		// 获取配置
		var config_res = await this.sendApi('/order/auto/config');
		if (config_res.code != 200) {
			return this.autoOrderInfo('获取自动下单配置失败');
		}
		try {
			if (message.start == 1) {
				// 如果进来已经有在跑了
				var ck_data = await this.storageGetPromise(['erptabid', 'auto_order']);
				if (ck_data.auto_order == 1) {
					// console.log('正在运行');
					this.autoOrderInfo(`已经有在运行程序 先点停止`);
					return ;
				}
				await this.StorageSetPromise('erptabid', sender.tab.id);
				this.autoOrderInfo(`${config_res.config.order_second} 秒后开始处理`);
				await this.delay(config_res.config.order_second * 1000);
				await this.StorageSetPromise('auto_order', 1); // 1标志着自动  2手动
			}
			
		} catch(e) {
			// 缓存失败
			console.log('缓存失败');
			return;
		}
		// 拿密码
		var data = await this.storageGetPromise(['paypwd', 'erptabid', 'auto_order']);
		if (data.auto_order != 1) {
			// 关闭了   检测地方 前台erp页面默认关闭   后台脚本监听关闭tab  当前url不在erp了 
			this.autoOrderInfo('自动下单已关闭');
			return;
		}

		var erptab = await this.getTabPromise(data.erptabid);
		// 检测是否还在erp页面
		// if (!erptab || erptab.url.indexOf("http://121.43.232.161:9527//#/order") == -1) {
		// 	// 关闭了 没找到tab  或者 不在erp了
		// 	this.closeAuto(message, sender, sendResponse);
		// 	return;
		// }

		if (!data.paypwd) {
			this.autoOrderInfo('先保存一下支付账号');
			chrome.scripting.executeScript({
				target: {tabId: data.erptabid},
				func: ()=> {
					alert('先保存一下支付账号');
				}
			});
			return ;
		}

		var res = await this.sendApi('/chrome/auto/order');
		if (res.code == 200) {
			message.order_data = res.data;
			message.manage = res.manage;
			message.has_next = 1;
			message.autoType = 'auto'; // 标志着自动下单
			var order_res = await this.handOrder(message, sender, sendResponse);
			if (order_res.code != 200) {
				this.autoOrderInfo(`订单号:【${message.order_data.platform_order_id}】 sku【${message.order_data.platform_sku_id}】 ${order_res.message}`, message.order_data.platform_order_id);
				await this.delay(3000);
				message.start = 0;
				message.autoType = 'auto';
				this.autoOrder(message, sender, sendResponse);
			}
		}

		if (res.code == 3001) {
			// 没有了 发消息
			this.autoOrderInfo(res.message);
			await this.delay(3000);
			message.start = 0;
			message.autoType = 'auto';
			this.autoOrder(message, sender, sendResponse);
		}
	}

	// 保存支付
	async savePay(message, sender, sendResponse) {
		// 删除支付宝相关cookie
		const cookies = await new Promise((resolve) => {
			chrome.cookies.getAll({domain: 'alipay.com'}, resolve);
		});

		for (const cookie of cookies) {
			if (cookie.domain.indexOf("alipay.com") != -1) {
				// console.log(cookie);
				const url = `http${cookie.secure ? 's' : ''}://${cookie.domain}${cookie.path}`;
				await new Promise((resolve)=> {
					chrome.cookies.remove({url, name:cookie.name}, resolve);
				});
			}
		}
		await this.StorageSetPromise('paypwd', message.pwd);
		await this.StorageSetPromise('payname', message.name);

		chrome.scripting.executeScript({
			target: {tabId: sender.tab.id},
			func: ()=> {
				alert('保存成功');
			}
		});
	}

	//自动付款
	async autoPay(message, sender, sendResponse) {



		// console.log('到支付了');
		var isbind = 0;
		// 自动支付标志
		const data = await this.storageGetPromise(['auto_pay', 'auto_order', 'payname', 'paypwd', 'orderSnBind', 'hand_order_tab']);
		// 检测是不是缓存的tab过来付款的
		if (data.hand_order_tab != sender.tab.id) {
			return this.autoOrderInfo('支付时采购页面检测出错 不要多开采购页面');
		}


		// 检测3次 是否成功
		for (var i = 0; i < 6; i++) {

			var check_bind = await this.storageGetPromise(['hand_order_sn', 'platform_order_id']);
			if (check_bind.hand_order_sn != '') {
				isbind = 1;
				break;
			}
			await this.delay(1000);
			console.log(`检测 ${i+1} 次`);
		}

		if (isbind == 0) {
			return this.autoOrderInfo('缓存错误, 请重开');
		}

		console.log(`${check_bind.hand_order_sn} === ${check_bind.platform_order_id} === 绑定了`);
		// if (data.auto_pay == 1 && data.auto_order == 1) { // 是自动下单才自动填密码
		if (data.auto_pay == 1) { // 不是自动下单也自动填密码
		// if (1) { // 测试用
			chrome.scripting.executeScript({
				target: {tabId: sender.tab.id},
				func: (name, pwd, data) => {
					// 监听页面变化
					function observeUrlChanges(callback) {
					  let lastUrl = window.location.href;
					  
					  const observer = new MutationObserver(function() {
					    if (window.location.href !== lastUrl) {
					      lastUrl = window.location.href;
					      callback(lastUrl);
					    }
					  });
					  
					  observer.observe(document, {subtree: true, childList: true});
					}
					function waitForElement(selector, callback) {
				        if (document.querySelector(selector)) {
				            callback();
				        } else {
				            const observer = new MutationObserver(() => {
				                if (document.querySelector(selector)) {
				                    callback();
				                    observer.disconnect();
				                }
				            });
				            observer.observe(document.documentElement, {
				                childList: true,
				                subtree: true
				            });
				        }
				    }
				    function typeCharacter(password, index, input) {
				    	
		                if (index < password.length) {
		                    const char = password[index];
		                    input.focus();
		                    const event = new KeyboardEvent('keydown', {
		                        key: char,
		                        code: 'Key'+ char.toUpperCase(),
		                        bubbles: true,
		                        cancelable: true,
		                        view: window
		                    });

		                    input.dispatchEvent(event);
		                    input.value += char;

		                    const inputEvent = new Event('input', { bubbles: true });

		                    input.dispatchEvent(inputEvent);
		                    
		                    index++;
		                    
		                    setTimeout(typeCharacter(password, index, input), 30000);
		                } else {
		                	document.querySelector('.adm-button-large').click();
		                }
		            }
				    const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
				    async function doSomething() {
				    	// 输入账号
				    	waitForElement('.my-adm-input', async () => {
				    		await delay(500);
				    		const input = document.querySelector('.adm-input-element');
				    		typeCharacter(name, 0, input)
				    	});

				    	// 点击 支付密码登录
				    	waitForElement('.toAccountLoginWrap___2ir3r', async () => {
				    		await delay(1000);
				    		const login_text = document.querySelector('.toAccountLoginWrap___2ir3r');
				    		login_text.click();
				    	});

				    	// 登入时的 下一步
				    	waitForElement('.adm-button-shape-default', async () => {
						    observeUrlChanges(async function(newUrl) {
						    	if (newUrl.includes('https://mclient.alipay.com/h5pay/accountLogin/index.html')) {
						    		await delay(2000);
						    		const login_input = document.querySelector('.my-passcode-input-native-input');
						    		// console.log(login_input, '找的输入框');
						    		typeCharacter(pwd, 0, login_input);
						    	}
						    })
				    	});

				    	// 点击确认付款 输入密码
				        waitForElement('.cashierPreConfirm__btn', async () => {
				        	// console.log('找到确认付款');
				            document.querySelector(".cashierPreConfirm__btn").click();

				            await delay(2000);
				            var index = 0;
				            const input = document.querySelector('.my-passcode-input-native-input');
				            typeCharacter(pwd, 0, input);
				        });

				        // 支付完成
				        waitForElement('.cashierActivity__finishBtn', async () => {
				        	// 发送订单完成绑定
				        	// chrome.runtime.sendMessage({greeting: 'payFinish'});
				        	await delay(3000)
				        	chrome.runtime.sendMessage({greeting: 'payFinish'});
				        	document.querySelector('.cashierActivity__finishBtn').children[0].click();
				        });
				    }
				    doSomething();
				    
				},
				args: [data.payname, data.paypwd, data]
			});
		} else if (data.auto_order == 1 && data.auto_pay == 2) {
			// 关闭
			chrome.tabs.remove(sender.tab.id);
			// 开启下一个
			var new_message = {
				order_data: {},
				autoType : 'auto'
			}
			await this.delay(2000);
			this.autoOrder(new_message, sender, sendResponse);
		} else if (data.auto_order != 1) {
			console.log('不是自动下单');
			// 不是自动支付
			chrome.scripting.executeScript({
				target: {tabId: sender.tab.id},
				func: () => {
					
					function observeUrlChanges(callback) {
					  let lastUrl = window.location.href;
					  
					  const observer = new MutationObserver(function() {
					    if (window.location.href !== lastUrl) {
					      lastUrl = window.location.href;
					      callback(lastUrl);
					    }
					  });
					  
					  observer.observe(document, {subtree: true, childList: true});
					}
					function waitForElement(selector, callback) {
				        if (document.querySelector(selector)) {
				            callback();
				        } else {
				            const observer = new MutationObserver(() => {
				                if (document.querySelector(selector)) {
				                    callback();
				                    observer.disconnect();
				                }
				            });
				            observer.observe(document.documentElement, {
				                childList: true,
				                subtree: true
				            });
				        }
				    }

				    async function doSomething() {
				    	// 支付完成
				        waitForElement('.cashierActivity__finishBtn', async () => {
				        	// 发送订单完成绑定
				        	// console.log('手动支付完成');
				        	// alert(2);
				        	chrome.runtime.sendMessage({greeting: 'payFinish'});
				        });
				        // waitForElement('.cashierPreConfirm__btn', async () => {
				        // 	alert(3);
				        // });
				        
				        // waitForElement('.my-passcode-input', async () => {
				        // 	alert(4);
				        // });
				        // waitForElement('.grid-input___QE1qT', async () => {
				        // 	alert(5);
				        // });

				        // 支付完成到这了 https://mclient.alipay.com/h5pay/cashierActivity/index.html
				        observeUrlChanges(function (newUrl) {
				        	if (newUrl.includes('https://mclient.alipay.com/h5pay/cashierActivity/index.html')) {
				        		alert('支付完成1');
				        		waitForElement('.cashierActivity__finishBtn', async() => {
				        			alert('支付完成');
				        			chrome.runtime.sendMessage({greeting: 'payFinish'});
				        		});
				        	}
				        });
				    }

				    doSomething();

				}
			});
		}
	}

	//支付完成
	async payFinish(message, sender, sendResponse) {
		// 获取缓存的订单号
		var storage_data = await this.storageGetPromise(['hand_order_sn', 'auto_order', 'hand_order_tab']);
		// 检测缓存中的tab是否出错  
		if (storage_data.hand_order_tab != sender.tab.id) {
			return this.autoOrderInfo('支付完成时检测下单tab缓存出错  请不要多开采购页面');
		}

		await this.StorageSetPromise('hand_order_tab', '');
		var storage_data = await this.storageGetPromise(['hand_order_sn', 'auto_order', 'hand_order_tab']);

		if (storage_data.hand_order_tab != '') {
			return this.autoOrderInfo('支付完成了 重置采购页面tab出错');
		}

		message.orderSn = storage_data.hand_order_sn;

		await this.orderSnAsync(message, sender, sendResponse);
		
		//如果是在自动下单中 开启下一个
		if (storage_data.auto_order == 1) {
			chrome.tabs.remove(sender.tab.id);
			const new_message = {
				autoType: 'auto',
				order_data: {}
			};
			this.autoOrder(new_message, sender, sendResponse);
		}
	}

	// 下单流程
	async handOrder(message, sender, sendResponse) {
		// message.autoType

		// hand_order_tab 为下单当前tabid

		var erpdata = await this.storageGetPromise(['erptabid', 'hand_order_tab']);
		var erptabid = 0;
		if (message.autoType == 'auto') {
			erptabid = erpdata.erptabid;
		} else {
			erptabid = sender.tab.id;
		}

		// 为了防止多开下单页面
		if (erpdata.hand_order_tab != '') {
			if (message.autoType == 'auto') {
				return {code: 300, message: '请先关闭所有采购页面'};
			} else {
				return chrome.scripting.executeScript({
					target: {tabId: erptabid},
					func: () => {
						alert('请先关闭所有采购页面');
					}
				});
			}
		}

		if (!message.order_data.real_user_name) {
			if (message.autoType == 'auto') {
				return {code: 300, message: '地址未解密'};
			} else {
				return chrome.scripting.executeScript({
					target: {tabId: erptabid},
					func: () => {
						alert('地址还没解密，点击小眼睛');
					}
				});
			}
		}

		if (message.autoType == 'auto') {
			this.autoOrderInfo(`开始自动下单【${message.order_data.platform_order_id}】【${message.order_data.platform_sku_id}】`, message.order_data.platform_order_id);
		}

		// 改地址
		const addrReqData = {
			platform_order_id: message.order_data.platform_order_id,
			platform_sku_id: message.order_data.platform_sku_id
		};
		var res = await this.sendApi('/chrome/order/addr/params', addrReqData);
		// console.log(res);
		if (res.code != 200) {
			if (message.autoType == 'auto') {
				return {code: 300, message: res.message};
			} else {
				return chrome.scripting.executeScript({
					target: {tabId: sender.tab.id},
					func: (res) => {
						alert(res.message);
					},
					args: [res]
				});
			}
			
			
		}
		var purchase = res.purchase;
		var manage = res.manage;
		var config = res.config;
		var params = res.params;
		var address = res.address;

		// 危险地址检测
		if (purchase.danger_address && purchase.danger_address == 1) {
			// 属于危险地址
			if (message.autoType == 'auto') {
				return {code: 400, message: `危险地址 === ${purchase.danger_info}`};
			} else {
				chrome.scripting.executeScript({
					target: {tabId: sender.tab.id},
					func: (purchase) => {
						alert(`危险地址 === ${purchase.danger_info}`);
					},
					args: [purchase]
				});
			}
		}


		//获取默认地址
		const storage_data = await this.storageGetPromise(['agent']);
		var purchase_account = false;
		const accounts = await this.getAccounts();
		for (var i = 0; i < accounts.length; i++) {
			const cookies = JSON.parse(accounts[i].cookies);
			await this.setPDDCookie(cookies);

			const html = await this.getRawDataHtml("https://mobile.yangkeduo.com/addresses.html");
			const rawData = this.getRawData(html);
			// console.log(rawData);
			if (!rawData) {
				// 掉线
				this.disAccount(accounts[i]);
				continue;
			}
			const addressList = rawData.stores.store.addressList;
			var address_id = 0;
			for (var j = 0; j < addressList.length; j++) {
				if (addressList[j].isDefault == 1) {
					address_id = addressList[j].addressId;
					break;
				}
			}
			if (address_id === 0) {
				break;
			}
			// console.log('拿到默认地址了');
			if (address_id != 0) {
				var purchase_account = accounts[i];
				break;
			}
		}
		// console.log(purchase_account);
		if (!purchase_account) {
			if (message.autoType == 'auto') {
				return {code: 400, message: '没有账号了'};
			} else {

				return chrome.scripting.executeScript({
					target: {tabId: erptabid},
					func: () => {
						alert('没有可用账号了');
					}
				});
			}
			
			
		}

		var updateAddrParams = {
			address: res.params.address,
			address_id: address_id,
			anti_content: '',
			check_region: true,
			city_id: res.params.pdd_city_id,
			community_address_request: {},
			district_id: res.params.pdd_district_id,
			is_default: "1",
			mobile: res.params.mobile,
			name: res.params.name,
			province_id: res.params.pdd_province_id
		};
		// 拿anti
		// const jsres = await this.sendApi('/chrome/js', {name: 'anti_content'});
		var jsresponse = await new Promise((resolve) => {
			chrome.tabs.sendMessage(erptabid, {greeting: 'getAnti'}, (response) => {
				// console.log(response);
				if (chrome.runtime.lastError) {
					console.warn(chrome.runtime.lastError.message);
        			resolve(null);
				} else {
					resolve(response);
				}
			})
		});
		updateAddrParams.anti_content = jsresponse;
		var pdd_res = await this.fetchAddress(updateAddrParams, purchase_account.pdd_user_id);
		if (pdd_res.success == false && pdd_res.error_code == 43080) {
			// 地址不匹配  再修正一次
			updateAddrParams.province_id = pdd_res.result.suggest_province_id;
			updateAddrParams.city_id = pdd_res.result.suggest_city_id;
			updateAddrParams.district_id = pdd_res.result.suggest_district_id

			pdd_res = await this.fetchAddress(updateAddrParams, purchase_account.pdd_user_id);
		}


		if (pdd_res.result !== true) {
			if (message.autoType == 'auto') {
				return {code: 300, message: '修改默认地址失败'};
			} else {
				return chrome.scripting.executeScript({
					target: {tabId: erptabid},
					func: () => {
						alert('修改默认地址失败');
					}
				});
			}
			
			
		}

		//给服务器绑定采购账号
		const bindData = {
			platform_order_id: purchase.platform_order_id,
			platform_sku_id: purchase.platform_sku_id,
			account_id: purchase_account.id
		};
		const bind_res = await this.sendApi('/chrome/purchase/bind', bindData);
		if (bind_res.code != 200) {
			if (message.autoType == 'auto') {
				return {code: 300, message: bind_res.message}; 
			} else {
				return chrome.scripting.executeScript({
					target: {tabId: sender.tab.id},
					func: (bind_res) => {
						alert(bind_res.message);
					},
					args: [bind_res]
				});
			}
		}
		var check_hand_tab = await this.storageGetPromise(['hand_order_tab']);
		console.log(check_hand_tab);
		// 为了防止多开下单页面
		if (check_hand_tab.hand_order_tab != '') {
			console.log('多开检测不通过');
			if (message.autoType == 'auto') {
				return {code: 300, message: '请先关闭所有采购页面'};
			} else {
				return chrome.scripting.executeScript({
					target: {tabId: erptabid},
					func: () => {
						alert('请先关闭所有采购页面');
					}
				});
			}
		}
		console.log('多开检测通过了');
		// 缓存当前下单
		try {
			console.log('缓存下单信息');
			await this.StorageSetPromise('purchase_id', purchase.id); // 用于付款前检测
			await this.StorageSetPromise('platform_order_id', purchase.platform_order_id);
			await this.StorageSetPromise('platform_sku_id', purchase.platform_sku_id);
			await this.StorageSetPromise('link_skuID', purchase.link_skuID);
			await this.StorageSetPromise('hand_order_sn', '');
			// 如果开着全局
			if (manage.all_auto_pay == 1) {
				await this.StorageSetPromise('auto_pay', 1);
			} else {
				await this.StorageSetPromise('auto_pay', purchase.auto_pay);
			}
			
			
		} catch(e) {
			if (message.autoType == 'auto') {
				return {code: 300, message: '缓存失败'};
			} else {
				return chrome.scripting.executeScript({
					target: {tabId: erptabid},
					func: () => {
						alert('缓存失败');
					}
				});
			}
		}

		console.log('开始检测缓存');
		//检测缓存
		var check_storage = await this.storageGetPromise(['platform_order_id', 'hand_order_sn']);
		if (check_storage.platform_order_id != purchase.platform_order_id || check_storage.hand_order_sn != '') {
			// 关闭采购页面， 提示

			if (message.autoType == 'auto') {
				return {code: 300, message: '缓存失败'};
			} else {
				return chrome.scripting.executeScript({
					target: {tabId: erptabid},
					func: () => {
						alert('缓存失败');
					}
				});
			}
		}
		console.log('开始检测缓存检测通过');
		// 检测数量
		if (config.is_number) {
			if (purchase.sku_cnt > config.sku_number) {
				// 如果采购量大于设置的
				if (message.autoType == 'auto') {
					return {code: 300, message: `【${purchase.platform_order_id}】 采购数量大于设置数量 跳过采购`}
				}
			}
		}
		var buy_count = purchase.sku_cnt;

		if (purchase.min_count > purchase.sku_cnt) {
			// 跟着最小采购量走
			buy_count = purchase.min_count;
		}
		console.log('开始准备下单');
		const orderpurchase_url = "https://mobile.yangkeduo.com/order_checkout.html?sku_id="+ purchase.link_skuID +"&goods_id="+ purchase.target_goods_id +"&goods_number=" + buy_count;
		chrome.tabs.create({url: orderpurchase_url, active: true}, async (tab)=> {
			const onUpdatedListener = async (updatedTabId, changeInfo) => {
				if (updatedTabId === tab.id && changeInfo.status === 'complete') {

					var check_hand_tab = await this.storageGetPromise(['hand_order_tab']);
					console.log(check_hand_tab);
					if (check_hand_tab.hand_order_tab != tab.id && check_hand_tab.hand_order_tab != '') {
						chrome.runtime.sendMessage({greeting: 'closePDDOrder', message: `【${purchase.platform_order_id}】多开采购检测不通过`, platform_order_id: purchase.platform_order_id});
						return this.autoOrderInfo('多开下单页面检测不通过，请重试点击清除下单缓存记录', purchase.platform_order_id);
					}

					await this.StorageSetPromise('pddtabid', tab.id);
					await this.StorageSetPromise('hand_order_tab', tab.id);

					var check_hand_tab = await this.storageGetPromise(['hand_order_tab']);
					if (check_hand_tab.hand_order_tab != tab.id) {
						chrome.runtime.sendMessage({greeting: 'closePDDOrder', message: `【${purchase.platform_order_id}】多开采购检测不通过`, platform_order_id: purchase.platform_order_id});
						return this.autoOrderInfo('多开下单页面检测不通过，请重试点击清除下单缓存记录', purchase.platform_order_id);
					}
					console.log('多开缓存检测通过');
					chrome.tabs.onUpdated.removeListener(onUpdatedListener);
					//注入代码
					//利润
					console.log('开始检测 利润');
					const fee = purchase.real_price * purchase.sku_cnt * 0.01;

					const sku_arr = JSON.parse(purchase.sku_attrs);
					var sku_text = '';
					for (var i = 0; i < sku_arr.length; i++) {
						if (i == sku_arr.length) {
							sku_text = sku_text + sku_arr[i].attr_value
						} else {
							sku_text = sku_text + sku_arr[i].attr_value + ';';
						}
					}
					chrome.scripting.executeScript({
						target: {tabId: tab.id},
						func: (purchase) => {
							if (purchase.danger_address && purchase.danger_address == 1) {
								alert(`危险地址 === ${purchase.danger_info}`);
							}
						},
						args: [purchase]
					});
					chrome.scripting.executeScript({
						target: {tabId: tab.id},
						func: purchaseOriginHtml,
						args: [
					        sku_text, 
					        purchase.sku_cnt, 
					        purchase.real_price/100, 
					        purchase.thumb_img, 
					        address
					    ]
					});

					//检测缓存
					var check_storage = await this.storageGetPromise(['platform_order_id', 'hand_order_sn']);
					if (check_storage.platform_order_id != purchase.platform_order_id || check_storage.hand_order_sn != '') {
						// 关闭采购页面， 提示
						console.log('order_id_order_sn fail');
						if (message.autoType == 'auto') {
							return {code: 300, message: '缓存失败'};
						} else {
							return chrome.scripting.executeScript({
								target: {tabId: erptabid},
								func: () => {
									alert('缓存失败');
								}
							});
						}
					}
					console.log('下单时 订单缓存通过');
					chrome.scripting.executeScript({
						target: {tabId: tab.id},
						func: (inconfig, purchase, message, infee) => {
							// 一些检测
							// alert(0);
							var config = {
								is_profit: inconfig.is_profit,
								profit: inconfig.profit/100,
								is_profit_rate: inconfig.is_profit_rate,
								profit_rate: inconfig.profit_rate,
								is_number: inconfig.is_number,
								sku_number: inconfig.is_number,
							};
							var passOrder = 1;
							var auto_order = message.autoType;
							var fee = infee;
							var real_price = purchase.real_price * purchase.sku_cnt;

							var commission = 0;
							if (purchase.commission_amount) {
								commission = purchase.commission_amount;
							}
							var purchase_amount = parseFloat(document.querySelector("span.HApVUXCl").textContent.split('¥').join(''));
							
							var profit = real_price - purchase_amount*100 - commission - fee;

							var profit_p = ((profit / real_price) * 100).toFixed(2);

							const pay_infos = document.querySelector("div.fhvFseJO");
							var info_div = document.querySelector("span.ytvDn_JS");
							var span_e = document.createElement("span");
							var span_a = document.createElement("span");
							span_e.style.color = "white";
							span_e.style.zIndex = "10000";
							span_e.style.position = 'fixed';
							span_e.style.bottom = "80px";
							span_e.style.padding = "5px";

							span_a.style.color = "white";
							if (profit > 0) {
								span_e.style.backgroundColor = 'red';
								span_e.innerHTML =  profit_p +"%; 赚："+ (profit/100).toFixed(2);
								span_a.style.backgroundColor = 'red';
								span_a.innerHTML =  profit_p +"%; 赚："+ (profit/100).toFixed(2);
							} else {
								span_e.style.backgroundColor = 'green';
								span_e.innerHTML =  profit_p +"%; 亏："+ (profit/100).toFixed(2);
								span_a.style.backgroundColor = 'green';
								span_a.innerHTML =  profit_p +"%; 亏："+ (profit/100).toFixed(2);
							}
							document.body.appendChild(span_e);
							document.getElementById('csp-money').appendChild(span_a);

							if (config.is_profit) {
								// 检测利润
								if (profit < config.profit) {
									// 如果利润小于设置利润
									passOrder = 2;
									if (auto_order == 'auto') {
										chrome.runtime.sendMessage({greeting: 'closePDDOrder', message: `【${purchase.platform_order_id}】利润检测不通过关闭了`, platform_order_id: purchase.platform_order_id});
									}
									return 0;
								}
							}

							if (config.is_profit_rate) {
								if (profit_p < config.profit_rate) {
									// 利润率检测不通过
									passOrder = 3;
									if (auto_order == 'auto') {
										chrome.runtime.sendMessage({greeting: 'closePDDOrder', message: `【${purchase.platform_order_id}】利润率检测不通过关闭了`, platform_order_id: purchase.platform_order_id});
									}
									return 0;
								}
							}

							if (passOrder == 2) {
								alert('利润检测不通过');
								return 0;
							}

							if (passOrder == 3) {
								alert('利润率检测不通过');
								return 0;
							}
							// alert(1);
							// 这里做下领券
							const pay_ticket = document.querySelector('.EsbW5FUQ');
							if (pay_ticket) {
								pay_ticket.click();
								setTimeout(() => {
								    const get_ticket = document.querySelector('.sv_JzYS3');
									if (get_ticket) {
										get_ticket.click();
										// 如果是关注券
										setTimeout(() => {
											const guanzhuq = document.querySelector('.NwofgMp6');
											if (guanzhuq) {
												guanzhuq.click();
											}
										}, 700);
										
									}
							    }, 800);
								
							}

							const pays = pay_infos.children;
							for (var i = pays.length - 1; i >= 0; i--) {
								if (pays[i].textContent.indexOf("支付宝") != -1) {
									pays[i].click();
									break;
								}
							}
							console.log('到点支付了');
							if (auto_order == 'auto') {
								var btns = document.querySelectorAll('.IGIvwBGZ');
								console.log(btns);
								for (var i = 0; i < btns.length; i++) {
									if (btns[i].getAttribute('aria-label') == '立即支付'  && passOrder == 1) {
										setTimeout(() => {
											btns[i].click();
										}, 3000);
										break;
									}
								}
							}
							
						},
						args: [
							config,
							purchase,
							message,
							fee
						]
					});
					
				};
			};
			chrome.tabs.onUpdated.addListener(onUpdatedListener);
		});

		return {code: 200, message: '成功跳转'};
	}
	
	// 下单点付款绑定pdd订单号
	async orderSnBind(orderSn) {

		// 每次进入支付时把订单号缓存， 如果成功同步更新
		try {
			await this.StorageSetPromise('hand_order_sn', ''); //清空
			await this.StorageSetPromise('orderSnBind', 0); // 标志着绑定是否完成	
		} catch (e) {
			// console.log('ordersn 失败');
			return this.autoOrderInfo('缓存失败');
		}
		
		const data = await this.storageGetPromise(['platform_order_id', 'platform_sku_id', 'link_skuID', 'account_id', 'agent', 'hand_order_sn']);
		if (!data.platform_order_id) {
			return console.log('非系统下单');
		}

		if (data.hand_order_sn != '') {
			// 关闭下单
			var pdd_stroge = await this.storageGetPromise(['pddtabid']);
			chrome.tabs.remove(pdd_stroge.pddtabid);
			return this.autoOrderInfo('缓存失败');
		}
		var reqData = {
			platform_order_id: data.platform_order_id,
			platform_sku_id: data.platform_sku_id,
			order_sn: orderSn,
		};

		//获取订单情况
		const order_url = "https://mobile.yangkeduo.com/order.html?order_sn=" + orderSn;

		const html = await this.getRawDataHtml(order_url);
		const rawData = this.getRawData(html);

		if (rawData.data) {
			// 未支付的
			var bindReq = {
				pay_status: rawData.data.payStatus,
				order_status: rawData.data.orderStatus,
				order_sn: rawData.data.orderSn,
				platform_order_id: data.platform_order_id,
				platform_sku_id: data.platform_sku_id,
				amount: rawData.data.orderAmount
			};
		

			const orderGoods = rawData.data.orderGoods;
			for (var i = 0; i < orderGoods.length; i++) {
				if (orderGoods[i].skuId == data.link_skuID) {
					bindReq.product_cnt = orderGoods[i].goodsNumber;
					break;
				}
			}
			// console.log('新单号绑定');
			var res = await this.sendApi('/chrome/purchase/bind', bindReq);
			if (res.code == 200) {
				console.log('未支付绑定成功');
				await this.StorageSetPromise('hand_order_sn', orderSn);
				await this.StorageSetPromise('orderSnBind', 1); // 绑定完成可以开始支付
				var check_order_sn = await this.storageGetPromise(['hand_order_sn', 'erptabid', 'pddtabid']);
				if (check_order_sn.hand_order_sn != orderSn) {
					return this.autoOrderInfo('缓存失败, 同步完成');
				}
			}
		} else {
			// 解析失败的情况 直接关闭付款页面
			return this.autoOrderInfo('当前解析失败');
		}
	}

	async saveRegions() {
		var accounts = await this.getAccounts();

		for (var i = 0; i < accounts.length; i++) {
			const cookies = JSON.parse(accounts[i].cookies);
			await this.setPDDCookie(cookies); //设置 cookie
			// 改地址
			// 获取所有省份
			const url = "https://mobile.yangkeduo.com/proxy/api/api/galen/v2/regions/1?pdduid=" + accounts[i].pdd_user_id
			const res_p = await this.fetchAddr(url);
			if (res_p.hasOwnProperty('error_code') && res_p.error_code == '40001') {
				//掉线
				this.disAccount(accounts[i]);
				continue;
			}
			var regions = [];
			if (res_p.hasOwnProperty('regions')) {
				regions = res_p.regions;
				const p_reqData = {
					regions : regions
				};
				const rp_res = await this.sendApi('/chrome/region/set', p_reqData);
			}

			for (var j = 0; j < regions.length; j++) {
				const c_url = "https://mobile.yangkeduo.com/proxy/api/api/galen/v2/regions/"+ regions[j].region_id + "?pdduid=" + accounts[i].pdd_user_id;
				const res_c = await this.fetchAddr(c_url);
				
				if (res_c.hasOwnProperty('error_code') && res_c.error_code == '40001') {
					//掉线
					this.disAccount(accounts[i]);
					break;
				}
				var c_regions = [];
				if (res_c.hasOwnProperty('regions')) {
					c_regions = res_c.regions;
					const c_reqData = {
						regions: c_regions
					};
					const rc_res = await this.sendApi('/chrome/region/set', c_reqData);
				}
				// 再循环把区数据缓存
				for (var k = 0; k < c_regions.length; k++) {
					const d_url = "https://mobile.yangkeduo.com/proxy/api/api/galen/v2/regions/"+ c_regions[k].region_id + "?pdduid=" + accounts[i].pdd_user_id;
					const res_d = await this.fetchAddr(d_url);
					if (res_d.hasOwnProperty('error_code') && res_d.error_code == '40001') {
						// 掉线
						this.disAccount(accounts[i]);
						break;
					}

					const d_regions = res_d.regions;
					const d_reqData = {
						regions: d_regions
					};
					await this.sendApi('/chrome/region/set', d_reqData);
				}
			}

		}
		
		// this.orderProcess(message, sender, sendResponse);
	}

	// 展示订单
	async showPurchaseOrder(message, sender, sendResponse) {
		await this.StorageSetPromise('auto_pay', 2);

		const reqData = {
			order_sn: message.order_sn
		};
		const res = await this.sendApi('/chrome/purchase/get', reqData);
		if (res.code != 200) {
			chrome.scripting.executeScript({
				target: {tabId: sender.tab.id},
				func: (res) => {
					alert(res.message);
				},
				args: [res]
			});
			return;
		}
		const cookies = JSON.parse(res.account.cookies);
		await this.setPDDCookie(cookies);

		// 缓存当前下单
		const purchase = res.purchase;
		try {
			await this.StorageSetPromise('platform_order_id', purchase.platform_order_id);
			await this.StorageSetPromise('platform_sku_id', purchase.platform_sku_id);
			await this.StorageSetPromise('link_skuID', purchase.link_skuID);
			await this.StorageSetPromise('order_sn', message.order_sn);
		} catch(e) {
			chrome.scripting.executeScript({
				target: {tabId: sender.tab.id},
				func: () => {
					alert('缓存失败');
				}
			});
			return;
		}

		const order_url = "https://mobile.yangkeduo.com/order.html?order_sn=" + message.order_sn;
		chrome.tabs.create({url: order_url, active: true}, async (tab)=> {});
	}


	// 自动订单同步信息
	async autoSendInfo(text, platform_order_id = 0, platform_sku_id = 0, status_code = 0) {
		var storage_data = await this.storageGetPromise(['autosenderptabid']);

		var currentDate = new Date();
		var currentDateTime = currentDate.toLocaleString();
		text = currentDateTime + ' ' + text;

		var reqData = {
			platform_order_id: platform_order_id,
			platform_sku_id: platform_sku_id,
			info: text,
		};
		this.sendApi('/order/auto/send/log', reqData);
		if (platform_order_id) {
			text = text + `<a style="color: #409EFF;" href="/#/order?platform_order_id=${platform_order_id}" target="_blank">查看订单</a>`
		}

		chrome.scripting.executeScript({
			target: {tabId: storage_data.autosenderptabid},
			func: (text, platform_order_id, status_code) => {
				var ul = document.getElementById('send-infos');
				var li = document.createElement('li');
				li.innerHTML = text;
				if (status_code == 500) {
					li.style.color = 'red';
				}
				if (ul.childElementCount > 1000) {
					ul.setHTMLUnsafe('');
				}
				ul.prepend(li);
			},
			args: [text, platform_order_id, status_code]
		});
	}
	// 自动发货信息
	async autoOrderInfo(text, platform_order_id = 0) {
		var storage_data = await this.storageGetPromise(['erptabid']);
		var currentDate = new Date();
		var currentDateTime = currentDate.toLocaleString();
		text = currentDateTime + ' ' + text;

		var reqData = {
			platform_order_id: platform_order_id,
			info: text
		};

		this.sendApi('/order/auto/log', reqData);
		chrome.scripting.executeScript({
			target: {tabId: storage_data.erptabid},
			func: (text) => {
				var ul = document.getElementById('autoorder-infos');
				var li = document.createElement('li');
				li.textContent = text;
				if (ul.childElementCount > 1000) {
					ul.setHTMLUnsafe('');
				}
				ul.prepend(li);
			},
			args: [text]
		});
	}
	// 不通过 关闭pdd自动下单
	async closePDDOrder(message, sender, sendResponse) {
		this.autoOrderInfo(message.message, message.platform_order_id);
		// 这里需要清除 多开tab
		await this.StorageSetPromise('hand_order_tab', '');
		var check = await this.storageGetPromise(['hand_order_tab']);
		if (check.hand_order_tab != '') {
			return this.autoOrderInfo('采购页面检测缓存失败 请点重置采购页面检测缓存');
		}

		chrome.tabs.remove(sender.tab.id);
		//再开 新的自动单
		var new_message = {start: 0, autoType: 'auto'};
		this.autoOrder(new_message, sender, {});
	}

	// 关闭自动发货
	async closeAutoSend(message, sender, sendResponse) {
		await this.StorageSetPromise('auto_send', 2); // 1打开 2关闭 结束循环
		this.autoSendInfo('已经关闭自动同步');
	}

	// 暂停自动发货
	async stopAutoSend() {
		await this.StorageSetPromise('auto_state', 2); // 1运行 2暂停
		this.autoSendInfo('暂停运行');
	}

	// 开启自动发货
	async startAutoSend() {
		await this.StorageSetPromise('auto_state', 1); // 1运行 2暂停
		this.autoSendInfo('已经开启自动同步');
	}
	// 自动发货
	async autoSendOrder(message, sender, sendResponse) {
		var config_res = await this.sendApi('/order/auto/send/config');
		if (config_res.code != 200) {
			return this.autoSendInfo('获取自动检测配置失败');
		}
		var config = config_res.config;
		var reqData = {
				autoSend: 1,
				page : 1
			}
		var storage_data = await this.storageGetPromise(['auto_send']);

		if (storage_data.auto_send == 1) {
			// 已经有循环了
			return this.autoSendInfo('有任务开着 点击关闭 关闭后台任务');
		}

		if (message.start == 1) {
			await this.StorageSetPromise('autosenderptabid', sender.tab.id);
			await this.StorageSetPromise('auto_send', 1); // 打开循环
			await this.StorageSetPromise('auto_state', 1); //  可运行
		}
		this.autoSendInfo('自动发货任务开始');
		// 获取采购单
		while (true) {
			var storage_data = await this.storageGetPromise(['auto_send', 'auto_state']);
			if (storage_data.auto_send != 1) {
				// 点了关闭
				break;
			}
			await this.delay(1500); // 等待1.5秒
			// if (storage_data.auto_state != 1) {
			// 	// 暂停状态一直循环
			// 	await this.delay(2000)
			// 	continue;
			// }

			while (true) {
				var storage_data = await this.storageGetPromise(['auto_send', 'auto_state']);
				await this.delay(1500);
				if (storage_data.auto_send != 1 || storage_data.auto_state != 1) {
					// 不在运行状态 跳出检查 是否打开
					break;
				}

				var res = await this.sendApi('/chrome/auto/send', reqData, 0);
				if (res.data.rows.length == 0) {
					reqData.page = 1;
					this.autoSendInfo('没有可以同步的数据了');
					chrome.tabs.sendMessage(sender.tab.id, {greeting: 'autoSendTime'});
					return 0;
					// this.autoSendInfo(`下一轮检测 ${config.minute}分钟后开始`);
					// var times = config.minute * 2;
					// for (var auto_i = times; auto_i > 0; auto_i--) {
					// 	var for_storage_data = await this.storageGetPromise(['auto_send', 'auto_state']);
					// 	if (for_storage_data.auto_send != 1 || for_storage_data.auto_state != 1) {
					// 		// 不在运行状态 跳出检查 是否打开
					// 		break;
					// 	}
					// 	this.autoSendInfo(`等待中 == ${auto_i/2} 分钟`);
					// 	await this.delay(30000);
					// }
					// continue;
				} else {
					reqData.page = reqData.page + 1;
				}

				for (var i = 0; i < res.data.rows.length; i++) {
					await this.delay(1500);
					var storage_data = await this.storageGetPromise(['auto_send', 'auto_state']);
					if (storage_data.auto_send != 1 || storage_data.auto_state != 1) {
					// 不在运行状态 跳出检查 是否打开
						break;
					}
					// this.autoSendInfo('开始检查订单号:' + res.data.rows[i].platform_order_id);
					await this.delay(1000);
					if (!res.data.rows[i].order_sn) {
						this.autoSendInfo('订单:【' + res.data.rows[i].platform_order_id + '】【'+ res.data.rows[i].platform_sku_id +'】 没有下单记录', res.data.rows[i].platform_order_id, res.data.rows[i].platform_sku_id, 500);
						continue;
					}
					//执行同步任务
					var new_message = {
						orderSn: res.data.rows[i].order_sn, // 同步检测取数据
						autoType: "auto", // 标注 自动
						platform_order_id: res.data.rows[i].platform_order_id
					};
					
					if (res.data.rows[i].check_pickup == 1) {
						new_message.check_pickup = 1;
					}
					var auto_res = await this.orderSnAsync(new_message, sender, sendResponse);
					if (auto_res.message == 'success') {
						this.autoSendInfo('订单:【' + res.data.rows[i].platform_order_id + '】【'+ res.data.rows[i].platform_sku_id +'】 === 采购【'+ res.data.rows[i].order_sn +'】 同步成功', res.data.rows[i].platform_order_id, res.data.rows[i].platform_sku_id, auto_res.code);
					} else {
						this.autoSendInfo(`订单【${res.data.rows[i].platform_order_id}】【${res.data.rows[i].platform_sku_id}】 === 采购【${res.data.rows[i].order_sn}】 ${auto_res.message}`, res.data.rows[i].platform_order_id, res.data.rows[i].platform_sku_id, auto_res.code);
					}
					
				}
			}
			
		}
	}

	// 联系上家
	async orderMall(message, sender, sendResponse) {
		const reqData = {
			order_sn: message.order_sn
		};
		const res = await this.sendApi('/chrome/purchase/get', reqData);
		if (res.code != 200) {
			return chrome.scripting.executeScript({
				target: {tabId: sender.tab.id},
				func: (res) => {
					alert(res.message);
				},
				args: [res]
			});
		}
		const cookies = JSON.parse(res.account.cookies);
		await this.setPDDCookie(cookies);

		var purchase = res.purchase;
		const mall_url = `https://mobile.yangkeduo.com/chat_detail.html?order_sn=${purchase.order_sn}&mall_id=${purchase.mall_id}&from=order`;
		chrome.windows.create({
			url: mall_url, // 要打开的URL
			type: 'normal', // 可以是 'normal', 'popup', 'panel', 或 'app'
			width: 500,    // 窗口宽度
			height: 800,   // 窗口高度
			left: 100,     // 距离屏幕左侧的位置（可选）
			top: 100       // 距离屏幕顶部的位置（可选）
		}, function(newWindow) {
		  	// 回调函数，newWindow包含新窗口的信息
		  	// console.log('新窗口已创建:', newWindow);
		});
	}

	// 订单单独同步
	async orderSnAsync(message, sender, sendResponse) {
		const reqData = {
			order_sn: message.orderSn
		};
		// console.log('获取账号');
		const res = await this.sendApi('/chrome/purchase/get', reqData);
		if (res.code != 200) {
			if (message.autoType == "auto") {
				// 写日志
				return {code: 300, message: res.message};
			} else {
				if (message.autoType == 'auto') {
					return {code: 300, message: res.message};
				} else {
					return chrome.scripting.executeScript({
						target: {tabId: sender.tab.id},
						func: (res) => {
							alert(res.message);
						},
						args: [res]
					});
				}
			}
			
			return;
		}
		const cookies = JSON.parse(res.account.cookies);
		await this.setPDDCookie(cookies);
		
		var purchase = res.purchase;

		const order_url = "https://mobile.yangkeduo.com/order.html?order_sn=" + message.orderSn;	
		const html = await this.getRawDataHtml(order_url);
		const rawData = this.getRawData(html);

		if (!rawData) {
			if (message.autoType == 'auto') {
				return {code: 300, message: '解析失败, 有可能掉线了 查看一下账号'};
			} else {
				return chrome.scripting.executeScript({
						target: {tabId: sender.tab.id},
						func: () => {
							alert('解析失败请重试');
						}
					});
			}
			
			return ;
		}

		var bindData = {
			purchase_id: res.purchase.id,
			amount: rawData.data.orderAmount,
			order_status: rawData.data.orderStatus,
			pay_status: rawData.data.payStatus,
			pay_time: rawData.data.payTime,
			chat_status: rawData.data.chatStatusPrompt,
			mall_id: rawData.data.mallId
		};

		// console.log('开始检测是否有取件码');



		// 2状态是使用同步单的
		if (rawData.data.chatStatusPrompt == "待收货" && rawData.data.expressInfo && rawData.data.expressInfo.traces.length > 0 && (message.check_pickup || purchase.check_pickup) ) {
			// 循环看看有没有 入柜 等 判断取件码
			// console.log('进入检测取件码');
			var is_out = false; //已经取出
			var is_pickup = false;
			var is_return = false;
			var is_sign = false;
			for (var i = 0; i < rawData.data.expressInfo.traces.length; i++) {
				if (rawData.data.expressInfo.traces[i].status == "IN_CABINET") {
					is_pickup = true;
				}
				if (rawData.data.expressInfo.traces[i].status == "SIGN") {
					is_sign = true;
				}
				if (rawData.data.expressInfo.traces[i].status == "RETURN") {
					is_return = true;
				}

				if (rawData.data.expressInfo.traces[i].status == "OUT_CABINET") {
					is_out = true;
				}
			}

			if (is_pickup && !is_return) {
				// 有取件码
				// console.log('有取件码', message.orderSn);
				var ex_url = `https://mobile.yangkeduo.com/goods_express.html?order_sn=${message.orderSn}`;
				const ex_html = await this.getRawDataHtml(ex_url);
				const ex_rawData = this.getRawData(ex_html);
				if (ex_rawData && ex_rawData.store && ex_rawData.store.cabinetData && !ex_rawData.store.cabinetData.cnInOutBound && ex_rawData.store.cabinetData.status != 0) {
					if (ex_rawData.store.cabinetData.code != 'undefined') {
						bindData.pickup = ex_rawData.store.cabinetData.code + '|' + ex_rawData.store.cabinetData.companyName + ex_rawData.store.cabinetData.address;
					}
				}

				if (ex_rawData && ex_rawData.store && ex_rawData.store.cabinetData && ex_rawData.store.cabinetData.cnInOutBound) {
					if (ex_rawData.store.cabinetData.cnInOutBound.display != 'undefined') {
						bindData.pickup = ex_rawData.store.cabinetData.cnInOutBound.display + '|' + ex_rawData.store.cabinetData.cnInOutBound.address;
					}
					// console.log(bindData.pickup, '取件码');
				}
			} else {
				// console.log('没有取件码');
			}

			if (!is_pickup && is_sign) {
				// 已经签收无取件码
				bindData.async_end = 1; // 标志着 同步单已经签收 且无取件码相关
			}

			if (is_return) {
				bindData.async_return = 1; // 被退回
			}

			if (is_out) {
				bindData.async_out = 1; // 快递被取出
			}

			if (is_sign) {
				bindData.async_end = 1; // 签收
			}
		}

		// 另一种取件码方式
		if (!bindData.pickup) {
			var lastTrace = '';

			if (rawData.data && rawData.data.express && rawData.data.express.lastTrace) {
				lastTrace = rawData.data.express.lastTrace;
			}

			if (lastTrace.indexOf('取件码') === 0) {
				var last_arr = lastTrace.split(' ');
				if (last_arr.length == 2) {
					bindData.pickup = last_arr[0] + '|' + last_arr[1];
				}
			}
		}

		// console.log('开始检查售后');
		if (rawData.data.afterSales !== undefined) {
			// bindData.aftersales = rawData.data.afterSales;
			const aftersale_url = 'https://mobile.yangkeduo.com/complaints_new_detail.html?after_sales_id=' + rawData.data.afterSales.afterSalesId;
			const after_html = await this.getRawDataHtml(aftersale_url);
			const aftersale_rawData = this.getRawData(after_html);
			if (!aftersale_rawData) {
				if (message.autoType == 'auto') {
					return {code: 300, message: '售后解析失败'};
				} else {
					return chrome.scripting.executeScript({
						target: {tabId: sender.tab.id},
						func: () => {
							alert('售后解析失败请重试');
						}
					});
				}
			}
			// console.log('获取逆向物流');
			// 获取逆向物流
			var return_tracking_number = '';
			var ship_url = '';
			for (var i = 0; i < aftersale_rawData.store.detailData.length; i++) {
				if (aftersale_rawData.store.detailData[i].resourceTag == "reverseTracking") {
					// 逆向物流情况
					for (var j = 0; j < aftersale_rawData.store.detailData[i].items.length; j++) {
						// console.log(aftersale_rawData.store.detailData[i].items[j].resourceTag);
						// if (aftersale_rawData.store.detailData[i].items[j].resourceTag && aftersale_rawData.store.detailData[i].items[j].resourceTag == 'trackingNumberV2') {
						// 	return_tracking_number = aftersale_rawData.store.detailData[i].items[j].elements.desc.subText;
						// }


						if (aftersale_rawData.store.detailData[i].items[j].url) {
							ship_url = aftersale_rawData.store.detailData[i].items[j].url;
						}
					}
				}
			}
			var aftersale = {
				aftersale_id: aftersale_rawData.store.afterSalesId,
				status: aftersale_rawData.store.afterSalesStatus,
				type: aftersale_rawData.store.afterSalesType,
			};

			if (ship_url) {
				ship_url = 'https://mobile.yangkeduo.com/' + ship_url;
				const ship_html = await this.getRawDataHtml(ship_url);
				const ship_rawData = this.getRawData(ship_html);
				console.log(ship_rawData.stores.store);
				aftersale.tracking_number = ship_rawData.stores.store.trackingNumber
				aftersale.shipping_name = ship_rawData.stores.store.traceData.shipping.shippingName
			}

			if (message.refund_amount) {
				aftersale.refund_amount = message.refund_amount;
				aftersale.question_desc = message.question_desc;
			}
			if (return_tracking_number) {
				aftersale.return_tracking_number = return_tracking_number;
			}
			bindData.aftersale = aftersale;
		}


		if (rawData.data.expressInfo) {
			bindData.shipping_name = rawData.data.expressInfo.shippingName;
			bindData.tracking_number = rawData.data.expressInfo.trackingNumber;
		}

		if (message.is_log == 1) {
			bindData.is_log = 1;
		}
		const bind_res = await this.sendApi('/chrome/purchase/bind', bindData);
		// console.log('绑定数据');
		if (bind_res.code == 4001) {
			// 没有设置好快递
			if (message.autoType == 'auto') {
				return {code: 500, message: `【${res.purchase.platform_order_id}】没有找到对应快递名称， 去快递匹配中设置【${rawData.data.expressInfo.shippingName}】`};
			} else {
				if (sender.tab.id != 0) {
					return chrome.scripting.executeScript({
						target: {tabId: sender.tab.id},
						func: (res) => {
							alert(`【${res.purchase.platform_order_id}】没有找到对应快递名称， 去快递匹配中设置【${rawData.data.expressInfo.shippingName}】`);
						},
						args: [res]
					});
				}
			}
		}

		if (bind_res.code == 200) {
			// 通知erp刷新
			// console.log('绑定数据成功');
			if (message.autoType == 'auto') {
				console.log('自动同步');
				return {code: 200, message: bind_res.message, rawData: rawData};
			} else {
				if (sender.tab.id != 0) {
					chrome.tabs.sendMessage(sender.tab.id, {greeting: 'detailRefresh', detail: res.purchase.id});
				}
			}
		} else {
			if (message.autoType == 'auto') {
				return {code: bind_res.code, message: `【${res.purchase.platform_order_id}】 ${bind_res.message}`};
			} else {
				if (sender.tab.id != 0) {
					return chrome.scripting.executeScript({
						target: {tabId: sender.tab.id},
						func: (res, bind_res) => {
							alert(`【${res.purchase.platform_order_id}】 ${bind_res.message}】`);
						},
						args: [res, bind_res]
					});
				}
			}
		}
	}

	// 查看上家物流
	async checkShip(message, sender, sendResponse) {
		const reqData = {
			order_sn: message.order_sn
		};
		const res = await this.sendApi('/chrome/purchase/get', reqData);
		if (res.code != 200) {
			return chrome.scripting.executeScript({
				target: {tabId: sender.tab.id},
				func: (res) => {
					alert(res.message);
				},
				args: [res]
			});
		}
		const cookies = JSON.parse(res.account.cookies);
		await this.setPDDCookie(cookies);

		// 获取html
		const order_url = "https://mobile.yangkeduo.com/order.html?order_sn=" + message.order_sn;
		const html = await this.getRawDataHtml(order_url);
		const rawData = this.getRawData(html);
		if (!rawData) {
			chrome.scripting.executeScript({
				target: {tabId: sender.tab.id},
				func: () => {
					var li = document.createElement('li');
					li.textContent = '可能掉线了 去采购账号管理重新登录';
					document.querySelector('#ship-infos').appendChild(li);
				}
			});
			return this.disAccount(res.account);
		}

		var traces = rawData.data.expressInfo.traces;
		// console.log(traces);
		for (var i = 0; i < traces.length; i++) {
			chrome.scripting.executeScript({
				target: {tabId: sender.tab.id},
				func: (trace) => {
					var li = document.createElement('li');
					li.textContent = trace.displayTime+ ' | '+trace.info;
					document.querySelector('#ship-infos').appendChild(li);
				},
				args: [traces[i]]
			});
		}
	}
	// 查看退货物流
	async refundShip(message, sender, sendResponse) {
		const aftersale_id = message.aftersale_id;
		const order_sn = message.order_sn;

		var reqData = {
			order_sn: order_sn
		};
		const res = await this.sendApi('/chrome/purchase/get', reqData);

		const cookies = JSON.parse(res.account.cookies);
		await this.setPDDCookie(cookies);

		var url = `https://mobile.yangkeduo.com/complaints_new_detail.html?after_sales_id=${aftersale_id}`;
		const html = await this.getRawDataHtml(url);
		const rawData = this.getRawData(html);
		if (!rawData) {
			// 解析失败
			chrome.scripting.executeScript({
				target: {tabId: sender.tab.id},
				func: () => {
					var li = document.createElement('li');
					li.textContent = '解析失败 ， 可能掉线了';
					document.querySelector('#ship-infos').appendChild(li);
				}
			});
			this.disAccount(res.account);
			return ;
		}

		var ship_url = '';
		for (var i = 0; i < rawData.store.detailData.length; i++) {
			if (rawData.store.detailData[i].resourceTag == 'reverseTracking') {
				//ship_url = rawData.store.detailData[i].url;
				// 找到跳转看物流url
				for (var j = 0; j < rawData.store.detailData[i].items.length; j++) {
					if (rawData.store.detailData[i].items[j].url) {
						ship_url = rawData.store.detailData[i].items[j].url;
						break;
					}
				}
				break;
			}
		}

		if (ship_url == '') {
			// 还没退货
			return chrome.scripting.executeScript({
				target: {tabId: sender.tab.id},
				func: () => {
					var li = document.createElement('li');
					li.textContent = '还没退货';
					document.querySelector('#ship-infos').appendChild(li);
				}
			});
		}

		ship_url = 'https://mobile.yangkeduo.com/' + ship_url;
		const ship_html = await this.getRawDataHtml(ship_url);
		const ship_rawData = this.getRawData(ship_html);
		var traces = ship_rawData.stores.store.traceData.shipping.traces;
		var shippingName = ship_rawData.stores.store.traceData.shipping.shippingName;
		var trackingNumber = ship_rawData.stores.store.traceData.shipping.trackingNumber;
		

		for (var i = 0; i < traces.length; i++) {
			chrome.scripting.executeScript({
				target: {tabId: sender.tab.id},
				func: (trace) => {
					var li = document.createElement('li');
					li.textContent = trace.info;
					document.querySelector('#ship-infos').appendChild(li);
				},
				args: [traces[i]]
			});
		}

		chrome.scripting.executeScript({
			target: {tabId: sender.tab.id},
			func: (shippingName) => {
				var li = document.createElement('li');
				li.textContent = shippingName;
				document.querySelector('#ship-infos').appendChild(li);
			},
			args: [shippingName]
		});
		chrome.scripting.executeScript({
			target: {tabId: sender.tab.id},
			func: (trackingNumber) => {
				var li = document.createElement('li');
				li.textContent = trackingNumber;
				document.querySelector('#ship-infos').appendChild(li);
			},
			args: [trackingNumber]
		});
	}

	// 申请售后
	async afterSaleHand(message, sender, sendResponse) {
		const order_sn = message.order_sn;
		
		var reqData = {
			order_sn : message.order_sn
		};
		const res = await this.sendApi('/chrome/purchase/get', reqData);

		const cookies = JSON.parse(res.account.cookies);
		await this.setPDDCookie(cookies);

		const type = message.type;
		var type_o = 0;
		if (type == 'RETURN') {
			type_o = 2;
			//测试
			//return this.autoAftersaleItem(message, sender, sendResponse);
		} else if (type == 'REFUND') {
			type_o = 1;

			// 测试
			//return this.autoAftersaleItem(message, sender, sendResponse);
		}

		const aftersale_url = "https://mobile.yangkeduo.com/complaint.html?order_sn=" + order_sn + '&after_sales_type=' + type_o;

		chrome.tabs.create({url: aftersale_url, active: true});
	}

	// 显示售后详情
	async afterSaleDetail(message, sender, sendResponse) {
		const aftersale_id = message.aftersale_id;

		var reqData = {
			order_sn: message.order_sn
		};
		const res = await this.sendApi('/chrome/purchase/get', reqData);

		const cookies = JSON.parse(res.account.cookies);
		await this.setPDDCookie(cookies);

		const aftersale_detail_url = `https://mobile.yangkeduo.com/complaints_new_detail.html?after_sales_id=${aftersale_id}`;
		chrome.tabs.create({url: aftersale_detail_url, active: true});
		// 查物流 https://mobile.yangkeduo.com/psnl_goods_help.html?shipping_id=44&after_sales_id=13820827757501&tracking_number=SF3176304673755&_t_module_name=assistant_waybill
	}
	// 自动售后消息
	async autoAfterInfo(text, tabid, after_sale_order_id = 0) {
		var currentDate = new Date();
		var currentDateTime = currentDate.toLocaleString();
		text = currentDateTime + ' ' + text;

		var reqData = {
			after_sale_order_id: after_sale_order_id,
			info_text: text
		};
		this.sendApi('/chrome/auto/after/log', reqData);
		chrome.scripting.executeScript({
			target: {tabId: tabid},
			func: (text) => {
				var ul = document.getElementById('after-log');
				if (ul.childElementCount > 1000) {
					ul.setHTMLUnsafe('');
				}
				var li = document.createElement('li');
				li.textContent = text;

				ul.prepend(li);
			},
			args: [text]
		});
	}

	async autoAfterClose(message, sender, sendResponse) {

		await this.StorageSetPromise('auto_after', 0);
		return this.autoAfterInfo('自动售后停止了', sender.tab.id);
	}

	// 自动售后
	async autoAfter(message, sender, sendResponse) {
		var storage_data = await this.storageGetPromise(['auto_after']);
		if (storage_data.auto_after == 1) {
			return this.autoAfterInfo('自动售后开着 请先关闭', sender.tab.id);
		}

		await this.StorageSetPromise('auto_after', 1);

		var reqData = { page : 1 };
		var resData = {};
		var after_config = false;
		var after_config_res = await this.sendApi('/aftersale/config');
		if (after_config_res.code != 200) {
			await this.StorageSetPromise('auto_after', 0);
			return this.autoAfterInfo('获取自动售后配置失败');
		}
		after_config = after_config_res.config;

		var times = 1;
		this.autoAfterInfo('自动售后开始', sender.tab.id);
		while (true) {
			if (times > after_config.times) {
				await this.StorageSetPromise('auto_after', 0);
				return this.autoAfterInfo(`轮询执行 ${after_config.times} 次 完成`);
			}

			var storage_data = await this.storageGetPromise(['auto_after']);
			if (storage_data.auto_after != 1) { this.autoAfterInfo('自动售后停止了', sender.tab.id); break; }

			resData = await this.sendApi('/chrome/auto/after', reqData);
			
			if (resData.data.length == 0) { times = times+1; this.autoAfterInfo('没有任务了下一轮开始', sender.tab.id); reqData.page = 1; await this.delay(5000); continue; }

			for (var i = 0; i < resData.data.length; i++) {

				var storage_data = await this.storageGetPromise(['auto_after']);
				if (storage_data.auto_after != 1) { break; }
				this.autoAfterInfo(`${after_config.after_second}秒后 开始处理【${resData.data[i].after_sale_order_id}】`, sender.tab.id, resData.data[i].after_sale_order_id);
				await this.delay(after_config.after_second * 1000);
				var storage_data = await this.storageGetPromise(['auto_after']);
				if (storage_data.auto_after != 1) { break; }
				var res = await this.autoAftersaleItem(resData.data[i], sender.tab.id);
				this.autoAfterInfo(`售后【${resData.data[i].after_sale_order_id}】, 处理结果 == ${res.message}`, sender.tab.id, resData.data[i].after_sale_order_id);
			}
			resData = {};
			reqData.page = reqData.page + 1;
		}
	}

	//自动售后操作 申请退货  或者 申请退款
	async autoAftersaleItem(aftersale, tabid) {
		// 请求接口 https://mobile.yangkeduo.com/proxy/api/api/vancouver/direct_auto_close_group?pdduid=7641635247528
		// close_group_type:5 不想拼了
		// group_order_id:"2975184255837171448"
		// order_sn:"250607-436585121331448"
		const account = aftersale.account;
		const purchase = aftersale.purchase;

		try {
			const cookies = JSON.parse(account.cookies);
			await this.setPDDCookie(cookies);
		} catch(e) {
			return {code: 500, message: '账号登录失败'}
		}
		

		// 读取订单数据
		var rawData = false;
		var async_message = {orderSn: purchase.order_sn, autoType: 'auto'};
		var async_res = await this.orderSnAsync(async_message, {tab: {id: 0}}, {});
		
		if (async_res.code == 200) {
			rawData = async_res.rawData;
		} else {
			// console.log(async_res);
			return async_res;
		}

		this.autoAfterInfo(`【${aftersale.after_sale_order_id}】 === ${async_res.message}`, tabid, aftersale.after_sale_order_id);
		if (!rawData) {
			await this.disAccount(account);
			return {code: 500, message: '解析失败可能掉线'};
		}

		// 如果是撤销售后
		if (aftersale.status == 'USER_CANCELD') {
			if (rawData.data.afterSales.afterSalesStatus == 6) {
				return {code: 400, message: `采购单【${purchase.order_sn}】 已经撤销过售后了`}
			}

			if (rawData.data.afterSales.afterSalesStatus == 5) {
				return {code: 400, message: `采购单【${purchase.order_sn}】 已经退款成功了 `}
			}
			return await this.cancelRefund(aftersale, rawData);
		}

		if (rawData.data.afterSales && rawData.data.afterSales.afterSalesStatus != 6) {
			// 已经有退款了
			return {code: 300, message: `采购单【${purchase.order_sn}】 已经申请过售后了, 跳过`};
		}

		// 查看是否拼单成功
		if (rawData.data.chatStatusPrompt == '待分享') {
			// 未成功
			// console.log('待分享取消拼单');
			return await this.shareRefund(aftersale, rawData)
		} else {
			// 已经成功
			// console.log('申请售后');
			return await this.checkRefund(aftersale, rawData);
		}
	}

	getQuestionType(aftersale, rawData) {

		// console.log(aftersale.reason_text);
		switch(aftersale.reason_text) {
			case '不想要了':
				if (rawData.data.chatStatusPrompt == '拼单成功，待发货') {
					return 66;
				} 
				if (rawData.data.chatStatusPrompt == '待收货' && aftersale.type == 'REFUND') {
					// 中途仅退款  197
					return 197
				}
				return 88;
				break;
			case '与商家协商一致退款':
				// 没找到
				return 88;
			case '买贵了':
				return 5000;
				break;
			case '做工粗糙/有瑕疵':
				// 没找到
				return 88;
			case '双方协商一致退款':
				//没找到
				return 88;
			case '发货太慢':
				return 193;
				break;
			case '品牌/材质/功能不符':
				return 288;
				break;
			case '品牌/材质/大小不符':
				return 288;
				break;
			case '品牌/材质/尺寸/容量不符':
				return 288;
				break;
			case '品牌/材质/尺寸不符':
				return 288;
				break;
			case '品牌/款式/规格/功能不符/不适配':
				//没找到
				return 88;
			case '商品异常-平台售后保障':
				return 95;
				break;
			case '商家少发/错发':
				return 83;
				break;
			case '商家少发/错发/漏发':
				return 83;
				break;
			case '商家少发/错发/漏发（含配件）':
				return 90;
				break;
			case '商家未按约定时间发货':
				//没找到
				return 88;
			case '商家错发':
				return 83;
				break;
			case '地址填错/不方便收货':
				return 5002;
				break;
			case '外包装污染/破损/变形':
				return 91;
			case '安装后不规整/稳固/做工粗糙/配件损坏':
				return 91;
			case '尺码/颜色/款式不合适':
				return 88;
			case '已在其他地方购买':
				return 88;
			case '快递一直未送达':
				return 196;
			case '收到商品污染/划痕/破损':
				return 91;
			case '空包裹':
				return 262;
				break;
			default: return 88;
		}
	}
	// 拼单成功退款 或 退货
	async checkRefund(aftersale, rawData) {

		const account = aftersale.account;
		const purchase = aftersale.purchase;
		var after_sales_type = '';
		var after_sales_trigger = '';
		var compensate_type = '';
		var question_type_value = '';
		var phone = aftersale.config.phone;

		if (aftersale.type == 'REFUND') {
			after_sales_type = 1;
			after_sales_trigger = 1;

			if (rawData.data.chatStatusPrompt == '待收货') {
				// 中途退款 trigger 3
				after_sales_trigger = 3;
			}

		} else if (aftersale.type == 'RETURN') {
			after_sales_type = 2;
			after_sales_trigger = 7;
		} else {
			return {code: 300, message: '未知售后类型，请手动查看'}
		}
		
		question_type_value = this.getQuestionType(aftersale, rawData);
		var cookies = JSON.parse(account.cookies);
		await this.setPDDCookie(cookies);
		// 先check 再退款 create
		//https://mobile.yangkeduo.com/proxy/api/api/lovers/pre_check?pdduid=7641635247528
		var check_url = `https://mobile.yangkeduo.com/proxy/api/api/lovers/pre_check?pdduid=${account.pdd_user_id}`;
		var check_data = {
			after_sales_trigger: after_sales_trigger,  // 1 仅退款  7 退货退款 3 中途仅退款
			after_sales_type: after_sales_type, // 1 仅退款 2 退货退款
			apply_amount:purchase.amount,
			compensate_type:999,
			images:[],
			new_refund_amount:purchase.amount,
			order_sn: purchase.order_sn,
			question_desc:"",
			question_type: question_type_value,
			refund_amount: purchase.amount,
			return_coupon_amount:0,
			user_phone: phone,
			user_ship_status:0
		};


		// 请求 等自动接口写完  目前可以绕过直接处理
		// await this.pddOrderPost(check_url, check_data);

		//再create
		// https://mobile.yangkeduo.com/proxy/api/after_sales/create?pdduid=7641635247528
		var create_url = `https://mobile.yangkeduo.com/proxy/api/after_sales/create?pdduid=${account.pdd_user_id}`;
		var create_data = {
			after_sales_type:1, // 1 仅退款 2 退货退款
			apply_amount:purchase.amount,
			coupon_return_control_type:0,
			images:[],
			is_lite:true,
			new_refund_amount:purchase.amount,
			order_sn:purchase.order_sn,
			question_desc:"1",
			question_type:question_type_value,
			refund_amount:purchase.amount,
			return_coupon_amount:0,
			user_phone: phone,
			user_ship_status:0
		};

		if (phone) {
			create_data.user_phone = phone;
		}

		// console.log(create_data);

		// 请求 等自动售后接口数据
		var pddres = await this.pddOrderPost(create_url, create_data);

		if (pddres.success == false) {
			return {code: 500, message: pddres.errorMsg}
		}

		// console.log('pddres', pddres);
		await this.delay(3000);
		var new_message = {
			orderSn: purchase.order_sn,
			autoType : 'auto'
		}
		await this.orderSnAsync(new_message, {tab: {id: 0}}, {});
		return {code: 200, message: '采购已申请售后'};
	}

	// 取消售后
	async cancelRefund(aftersale, rawData) {
		const account = aftersale.account;
		const purchase = aftersale.purchase;
		// console.log(rawData, '到这了');
		var cookies = JSON.parse(account.cookies);
		await this.setPDDCookie(cookies);

		const cancel_url = `https://mobile.yangkeduo.com/proxy/api/after_sales/cancel/${rawData.data.afterSales.afterSalesId}?pdduid=${account.pdd_user_id}`;
		var cancel_data = {version: 2};
		await this.pddOrderPost(cancel_url, cancel_data);
		await this.delay(2000);
		var new_message = {
			orderSn: purchase.order_sn,
			autoType: 'auto'
		}
		var res = await this.orderSnAsync(new_message, {}, {});
		return {code: 200, message: `采购单【${purchase.order_sn}】撤销了售后`};
	}

	// 未拼单成功退款
	async shareRefund(aftersale, rawData) {
		const account = aftersale.account;
		const purchase = aftersale.purchase;
		var cookies = JSON.parse(account.cookies);
		await this.setPDDCookie(cookies);
		const group_order_id = rawData.data.groupOrder.groupOrderId;
		const post_url = `https://mobile.yangkeduo.com/proxy/api/api/vancouver/direct_auto_close_group?pdduid=${account.pdd_user_id}`;
		const post_data = {
			close_group_type: 5,
			group_order_id: group_order_id,
			order_sn: purchase.order_sn
		};
		var res = await this.pddOrderPost(post_url, post_data);
		if (res.after_sales_id !== undefined) {
			var new_message = {
				orderSn: purchase.order_sn,
				autoType: 'auto'
			}
			await this.orderSnAsync(new_message, {tab: {id: 0}}, {});
			return {code: 200, message: '采购已申请售后'};
		} else {
			return {code: 500, message: '申请售后失败'};
		}
	}


	// 添加账号
	async addAccount(message, sender, sendResponse) {
		// 清除浏览器cookies
		const cookies = await new Promise((resolve) => {
			chrome.cookies.getAll({}, resolve);
		});

		for (const cookie of cookies) {
			if (cookie.domain.indexOf("yangkeduo.com") != -1) {
				// console.log(cookie);
				const url = `http${cookie.secure ? 's' : ''}://${cookie.domain}${cookie.path}`;
				await new Promise((resolve)=> {
					chrome.cookies.remove({url, name:cookie.name}, resolve);
				});
			}
		}

		chrome.tabs.create({url: "https://mobile.yangkeduo.com/personal.html", active: true})
	}


	
	// 切换登录
	async setAccount(message, sender, sendResponse) {
		// 清除浏览器cookies
		var cookies = await new Promise((resolve) => {
			chrome.cookies.getAll({}, resolve);
		});

		for (const cookie of cookies) {
			if (cookie.domain.indexOf("yangkeduo.com") != -1) {
				// console.log(cookie);
				const url = `http${cookie.secure ? 's' : ''}://${cookie.domain}${cookie.path}`;
				await new Promise((resolve)=> {
					chrome.cookies.remove({url, name:cookie.name}, resolve);
				});
			}
		}

		const reqData = {
			'acct_id': message.acct_id
		};
		var res = await this.sendApi('/chrome/account/set', reqData);
		if (res.code != 200) {
			chrome.scripting.executeScript({
				target: {tabId: sender.tab.id},
				func: (res)=> {
					alert(res.message);
				},
				args: [res]
			});
			return;
		}
		const new_cookies = JSON.parse(res.data.cookies);
		// console.log(new_cookies);
		await this.setPDDCookie(new_cookies);
		chrome.tabs.sendMessage(sender.tab.id, {greeting: 'accountRefresh'});
	}

};

const csp = new CSP();

export default csp;